use std::collections::HashMap;
use std::fs;

use crate::domain::Chart;

/// 获取Helm仓库中的图表
///
/// 根据URL获取Helm仓库中的图表
///
/// # 参数列表
/// * `url`          仓库URL           String
///
/// # 返回结果
/// * `data`         图表数据           `HashMap<String, Vec<Chart>>`
/// * `error`       获取失败的错误信息   String
#[tauri::command]
pub async fn get_charts(url: &str) -> Result<HashMap<String, Vec<Chart>>, String> {
    let client = reqwest::Client::new();
    let response = client
        .get(url)
        .send()
        .await
        .map_err(|e| format!("请求失败: {}", e))?;

    let data: HashMap<String, Vec<Chart>> = response
        .json()
        .await
        .map_err(|e| format!("解析失败: {}", e))?;

    Ok(data)
}

/// 下载Chart图表文件
///
/// 根据URL下载Chart图表文件
///
/// # 参数列表
/// * `url`          文件URL           String
///
/// # 返回结果
/// * `()`          下载成功           ()
/// * `error`       下载失败的错误信息   String
#[tauri::command]
pub fn download_file(url: &str) -> Result<(), String> {
    // 获取系统下载目录路径
    let download_dir = dirs::download_dir().ok_or_else(|| "无法获取系统下载目录".to_string())?;

    // 控制台打印url
    log::info!("Downloading file from URL: {}", url);

    // 确保download目录存在
    if !download_dir.exists() {
        fs::create_dir_all(&download_dir).map_err(|e| format!("下载目录创建失败: {}", e))?
    };

    // 从 URL 中提取最后一个斜杠后的文件名
    let file_name = url.split('/').last().unwrap_or("unknown_file");
    let file_path = download_dir.join(file_name);

    log::info!("Downloading file from URL: {}", url);
    log::info!("Saving file to: {}", file_path.display());

    match reqwest::blocking::get(url) {
        Ok(response) => match response.bytes() {
            Ok(bytes) => match fs::write(file_path, bytes) {
                Ok(_) => Ok(()),
                Err(e) => Err(format!("文件写入失败: {}", e)),
            },
            Err(e) => Err(format!("响应体读取失败: {}", e)),
        },
        Err(e) => Err(format!("文件获取失败: {}", e)),
    }
}
